package com.lyh.system.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

import com.lyh.common.core.domain.entity.SysUser;
import com.lyh.common.exception.ServiceException;
import com.lyh.common.exception.user.UserNotExistsException;
import com.lyh.common.utils.DateUtils;
import com.lyh.system.domain.Asset;
import com.lyh.system.domain.MemberRole;
import com.lyh.system.domain.Role;
import com.lyh.system.domain.req.SysMemberUserPageReq;
import com.lyh.system.domain.resp.SysMemberUserResp;
import com.lyh.system.domain.vo.MemberUserVo;
import com.lyh.system.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.lyh.system.mapper.SysMemberUserMapper;
import com.lyh.system.domain.SysMemberUser;

/**
 * 【请填写功能名称】Service业务层处理
 *
 * @author lyh
 * @date 2023-04-26
 */
@Service
public class SysMemberUserServiceImpl implements ISysMemberUserService {

    @Value(value = "${lyh.member.label:VIP}")
    private String memberLabel;

    @Autowired
    private SysMemberUserMapper sysMemberUserMapper;

    @Autowired
    IMemberRoleService memberRoleService;

    @Autowired
    IAssetService assetService;

    @Autowired
    IRoleService roleService;

    @Autowired
    ISysUserService sysUserService;

    /**
     * 查询【请填写功能名称】
     *
     * @param id 【请填写功能名称】主键
     * @return 【请填写功能名称】
     */
    @Override
    public SysMemberUser selectSysMemberUserById(Long id) {
        return sysMemberUserMapper.selectSysMemberUserById(id);
    }

    @Override
    public MemberUserVo selectMemberUserVoById(Long id) {
        SysMemberUser memberUser = sysMemberUserMapper.selectSysMemberUserById(id);
        MemberRole memberRole = memberRoleService.selectMemberRoleByMemberId(id);
        Asset asset = assetService.selectAssetByMemberId(id);
        MemberUserVo memberUserVo = new MemberUserVo();

        if (memberUser != null) {
            SysUser sysUser = sysUserService.selectUserById(memberUser.getUserId());
            memberUserVo.setName(sysUser.getNickName());
            memberUserVo.setInvitationCode(memberUser.getInvitationCode());
            if (memberRole != null) {
                Role role = roleService.selectRoleById(memberRole.getRoleId());
                memberUserVo.setRoleName(role.getRoleName());
                memberUserVo.setRoleCode(role.getRoleCode());
                memberUserVo.setLossTime(memberRole.getLossTime());
            }
            if (asset != null) {
                memberUserVo.setAccountBalance(asset.getAccountBalance());
             //   memberUserVo.setEquityLimit(asset.getEquityLimit());
                memberUserVo.setAssetEvidenceNum(asset.getAssetEvidenceNum());
                memberUserVo.setEquityPoints(memberUserVo.getEquityPoints());
                memberUserVo.setConsumerCouponNum(asset.getConsumerCouponNum());
            }
        }
        return memberUserVo;
    }

    @Override
    public SysMemberUser selectMemberByUserId(Long userId) {
        return sysMemberUserMapper.selectMemberByUserId(userId);
    }

    /**
     * 查询【请填写功能名称】列表
     *
     * @param req 【请填写功能名称】
     * @return 【请填写功能名称】
     */
    @Override
    public List<SysMemberUserResp> selectSysMemberUserList(SysMemberUserPageReq req) {
        return sysMemberUserMapper.selectSysMemberUserList(req);
    }

    /**
     * 新增【请填写功能名称】
     *
     * @param sysMemberUser 【请填写功能名称】
     * @return 结果
     */
    @Override
    public int insertSysMemberUser(SysMemberUser sysMemberUser) {
        sysMemberUser.setCreateTime(DateUtils.getNowDate());

        //检查是否已存在该用户
        SysMemberUser cond = new SysMemberUser();
        cond.setUserId(sysMemberUser.getUserId());
        List<SysMemberUser> list = sysMemberUserMapper.selectListByCond(cond);
        if (list != null && list.size() > 0) {
            throw new ServiceException("该用户已添加过！");
        }

        //会员ID生成规则 vip+当天日期+随机数字
        String date = DateUtils.getDate();
        Integer maxRomNum = sysMemberUserMapper.getMaxRomNum(date);
        if (maxRomNum == null || maxRomNum == 1) {
            maxRomNum = 100;
        }
        StringBuffer sb = new StringBuffer();
        sb.append(memberLabel).append(date.replace("-", "")).append(maxRomNum);

        //生成会员邀请码
        while (true) {
            String invitationCode = getInvitationCode(4);
            SysMemberUser memberUser = sysMemberUserMapper.selectSysMemberUserByCode(invitationCode);
            if (memberUser == null) {
                sysMemberUser.setInvitationCode(invitationCode);
                break;
            }
        }

        sysMemberUser.setRandomNum(maxRomNum);
        sysMemberUser.setMemberId(sb.toString());
        sysMemberUser.setCurrDate(DateUtils.dateTime(DateUtils.YYYY_MM_DD, date));
        return sysMemberUserMapper.insertSysMemberUser(sysMemberUser);
    }

    /**
     * 获取指定数量验证码
     *
     * @return
     */
    private String getInvitationCode(int length) {
        String CHARACTERS = "123456789ABCDEFGHIJKLMNPQRSTUVWXYZabcdefghijklmnpqrstuvwxyz";
        StringBuilder stringBuilder = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < length; i++) {
            int index = random.nextInt(CHARACTERS.length());
            stringBuilder.append(CHARACTERS.charAt(index));
        }
        return stringBuilder.toString();
    }

    /**
     * 修改【请填写功能名称】
     *
     * @param sysMemberUser 【请填写功能名称】
     * @return 结果
     */
    @Override
    public int updateSysMemberUser(SysMemberUser sysMemberUser) {
        if (sysMemberUser.getId() == null) {
            throw new ServiceException("未上传id");
        }
        sysMemberUser.setUpdateTime(DateUtils.getNowDate());
        SysMemberUser user = sysMemberUserMapper.selectSysMemberUserById(sysMemberUser.getId());
        user.setMemberLeve(sysMemberUser.getMemberLeve());
        user.setStatus(sysMemberUser.getStatus());
        user.setUserId(sysMemberUser.getUserId());
        return sysMemberUserMapper.updateSysMemberUser(user);
    }

    /**
     * 批量删除【请填写功能名称】
     *
     * @param ids 需要删除的【请填写功能名称】主键
     * @return 结果
     */
    @Override
    public int deleteSysMemberUserByIds(Long[] ids) {
        return sysMemberUserMapper.deleteSysMemberUserByIds(ids);
    }

    /**
     * 删除【请填写功能名称】信息
     *
     * @param id 【请填写功能名称】主键
     * @return 结果
     */
    @Override
    public int deleteSysMemberUserById(Long id) {
        return sysMemberUserMapper.deleteSysMemberUserById(id);
    }

    @Override
    public SysMemberUser selectMemberByMobile(String mobile) {
        return sysMemberUserMapper.selectMemberByMobile(mobile);
    }

    @Override
    public SysMemberUser selectSysMemberUserByCode(String invitationCode) {
        return sysMemberUserMapper.selectSysMemberUserByCode(invitationCode);
    }

    @Override
    public List<MemberUserVo> selectDownList(Long id) {
        SysMemberUser sysMemberUser = selectSysMemberUserById(id);
        if (sysMemberUser == null) {
            throw new UserNotExistsException();
        }
        List<SysMemberUser> sysMemberUsers = sysMemberUserMapper.selectDownList(sysMemberUser.getMemberLeve());
        List<MemberUserVo> memberUserVos = new ArrayList<>();
        if (sysMemberUsers != null && sysMemberUsers.size() > 0) {
            for (SysMemberUser memberUser : sysMemberUsers) {
                SysUser sysUser = sysUserService.selectUserById(memberUser.getUserId());
                MemberUserVo memberUserVo = new MemberUserVo();
                memberUserVo.setName(sysUser.getNickName());
                memberUserVo.setMemberId(memberUser.getId());
                memberUserVos.add(memberUserVo);
            }
        }
        return memberUserVos;
    }

    @Override
    public List<MemberUserVo> selectAllList() {
        List<MemberUserVo> memberUserVos = sysMemberUserMapper.selectAllList();
        return memberUserVos;
    }
}
